package br.com.iqt.advisor;

import br.com.iqt.*;
import br.com.iqt.exception.DbmsException;
import br.com.iqt.exception.HeuristicsSelectedException;
import br.com.iqt.exception.NegativeNumberException;
import br.com.iqt.exception.SqlInputException;
import br.com.iqt.util.Convertion;
import br.com.iqt.util.Indenter;
import br.com.iqt.zql.ParseException;
import java.awt.Dimension;
import java.awt.Font;
import java.io.*;
import java.sql.SQLException;
import java.util.ArrayList;
import java.util.Iterator;
import java.util.Properties;
import java.util.Vector;
import java.util.logging.Level;
import java.util.logging.Logger;
import javax.swing.JButton;
import javax.swing.JFileChooser;
import javax.swing.JLabel;
import javax.swing.JOptionPane;
import javax.swing.table.DefaultTableModel;

/**
 *
 * @author Arlino
 */
public class AdvisorGUI extends javax.swing.JFrame {

    //private HeuristicsSelected heuristicsSelect= new HeuristicsSelected();
    private ExecuteAdvisor executeAdvisor;
    private AgentRewriter agentRewriter;
    private ExecuteQuery sqlInThread, sqlOutThread;
    //salvam as infromações de conexão com o sgbd
    private final String fileNamePostgresql = "postgresql.properties";
    private final String fileNameSqlserver = "sqlserver.properties";
    private final String fileNameOracle = "oracel.properties";
    //salva o ultimo sgbd selecionado
    private final String fileNameSelectedDatabase = "selectedDatabase.properties";
    //salva o status do checkbox 'salvar senha'
    private final String fileNameStateCheckBoxSavePassword = "stateCheckBoxSavePassword.properties";
    //salva o status da opção identar sql
    private final String fileNameStateCheckBoxIdentSqlOut = "stateCheckBoxIdentSqlOut.properties";
    private final String fileNameStateCheckBoxIdentSqlIn = "stateCheckBoxIdentSqlIn.properties";
    //armazena a carga de trabalho
    private final String fileWorkloadFile = "WorkloadFile.txt";

    /**
     * Creates new form InteractiveAdvisor2
     */
    public AdvisorGUI() {
        initComponents();
        this.setExtendedState(AdvisorGUI.MAXIMIZED_BOTH);

        this.comboBoxBdms.setSelectedIndex(this.getSelectedDatabase());
        this.getDatabaseSettings();

        this.checkBoxIdentSQLOut.setSelected(this.getCheckBoxState(fileNameStateCheckBoxIdentSqlOut));
        this.checkBoxIdentSQLIn.setSelected(this.getCheckBoxState(fileNameStateCheckBoxIdentSqlIn));
        this.checkBoxSavePassword.setSelected(this.getCheckBoxState(fileNameStateCheckBoxSavePassword));
        this.setCheckBoxsAsSelected();

        this.labelNoConnection.setText("");
        this.labelExecutingRewrite.setText("");
        this.labelRewriteError.setText("");
        this.labelSqlInResult.setText("");
        this.labelSqlOutResult.setText("");
        this.labelMessengeRewrite.setText("");
        this.labelAddRewriteSettings.setText("");
        //this.labelAddRewriteSettingsAll.setText("");
//        this.labelMsgHeuristicApllied.setText("");
    }

    /**
     * This method is called from within the constructor to initialize the form.
     * WARNING: Do NOT modify this code. The content of this method is always
     * regenerated by the Form Editor.
     */
    @SuppressWarnings("unchecked")
    // <editor-fold defaultstate="collapsed" desc="Generated Code">//GEN-BEGIN:initComponents
    private void initComponents() {

        dialogRelatorio = new javax.swing.JDialog();
        jScrollPane4 = new javax.swing.JScrollPane();
        textAreaRelatorio = new javax.swing.JTextArea();
        buttonGroup1 = new javax.swing.ButtonGroup();
        dialogDefaultSettings = new javax.swing.JDialog();
        jScrollPane5 = new javax.swing.JScrollPane();
        textAreaDefaultSettings = new javax.swing.JTextArea();
        dialogCustomSettings = new javax.swing.JDialog();
        jPanel26 = new javax.swing.JPanel();
        jButton1 = new javax.swing.JButton();
        jPanel27 = new javax.swing.JPanel();
        jLabel17 = new javax.swing.JLabel();
        jPanel32 = new javax.swing.JPanel();
        jPanel33 = new javax.swing.JPanel();
        jLabel18 = new javax.swing.JLabel();
        jLabel19 = new javax.swing.JLabel();
        jLabel20 = new javax.swing.JLabel();
        jLabel21 = new javax.swing.JLabel();
        jLabel22 = new javax.swing.JLabel();
        jLabel23 = new javax.swing.JLabel();
        jLabel24 = new javax.swing.JLabel();
        jLabel25 = new javax.swing.JLabel();
        jLabel26 = new javax.swing.JLabel();
        jLabel27 = new javax.swing.JLabel();
        jLabel28 = new javax.swing.JLabel();
        jScrollPane6 = new javax.swing.JScrollPane();
        tableCustomHeuristics = new javax.swing.JTable();
        dialogExecutionPlan = new javax.swing.JDialog();
        jScrollPane7 = new javax.swing.JScrollPane();
        textAreaExecutionPlan = new javax.swing.JTextArea();
        panelNorth = new javax.swing.JPanel();
        panelNorthLeft = new javax.swing.JPanel();
        jScrollPane1 = new javax.swing.JScrollPane();
        listSqlsFromFile = new javax.swing.JList();
        jPanel9 = new javax.swing.JPanel();
        jLabel1 = new javax.swing.JLabel();
        jToggleButton2 = new javax.swing.JToggleButton();
        jButton5 = new javax.swing.JButton();
        panelNorthRight = new javax.swing.JPanel();
        jPanel4 = new javax.swing.JPanel();
        jLabel2 = new javax.swing.JLabel();
        comboBoxBdms = new javax.swing.JComboBox();
        jPanel8 = new javax.swing.JPanel();
        jPanel11 = new javax.swing.JPanel();
        jLabel4 = new javax.swing.JLabel();
        labelNoConnection = new javax.swing.JLabel();
        jPanel12 = new javax.swing.JPanel();
        jPanel22 = new javax.swing.JPanel();
        jLabel10 = new javax.swing.JLabel();
        textFieldServer = new javax.swing.JTextField();
        jPanel13 = new javax.swing.JPanel();
        jLabel6 = new javax.swing.JLabel();
        textFieldDatabase = new javax.swing.JTextField();
        jPanel23 = new javax.swing.JPanel();
        jLabel12 = new javax.swing.JLabel();
        textFieldPort = new javax.swing.JTextField();
        jPanel14 = new javax.swing.JPanel();
        jLabel8 = new javax.swing.JLabel();
        textFieldUser = new javax.swing.JTextField();
        jPanel15 = new javax.swing.JPanel();
        jLabel9 = new javax.swing.JLabel();
        textFieldPassword = new javax.swing.JTextField();
        jPanel1 = new javax.swing.JPanel();
        checkBoxSavePassword = new javax.swing.JCheckBox();
        jPanel16 = new javax.swing.JPanel();
        jPanel2 = new javax.swing.JPanel();
        jButton4 = new javax.swing.JButton();
        panelCenter = new javax.swing.JPanel();
        panelCenterLeft = new javax.swing.JPanel();
        panelCenterLeftTop = new javax.swing.JPanel();
        jScrollPane2 = new javax.swing.JScrollPane();
        textAreaSqlIn = new javax.swing.JTextArea();
        jPanel3 = new javax.swing.JPanel();
        jPanel17 = new javax.swing.JPanel();
        jLabel3 = new javax.swing.JLabel();
        jButton8 = new javax.swing.JButton();
        buttonExecuteSqlIn = new javax.swing.JButton();
        labelSqlInResult = new javax.swing.JLabel();
        jPanel7 = new javax.swing.JPanel();
        checkBoxIdentSQLIn = new javax.swing.JCheckBox();
        panelCenterLeftBottom = new javax.swing.JPanel();
        jPanel6 = new javax.swing.JPanel();
        jPanel21 = new javax.swing.JPanel();
        labelMessengeRewrite = new javax.swing.JLabel();
        labelRewriteError = new javax.swing.JLabel();
        labelExecutingRewrite = new javax.swing.JLabel();
        jPanel20 = new javax.swing.JPanel();
        jLabel5 = new javax.swing.JLabel();
        jButton9 = new javax.swing.JButton();
        buttonExecuteSqlOut = new javax.swing.JButton();
        labelSqlOutResult = new javax.swing.JLabel();
        jScrollPane3 = new javax.swing.JScrollPane();
        textAreaSqlOut = new javax.swing.JTextArea();
        jPanel5 = new javax.swing.JPanel();
        checkBoxIdentSQLOut = new javax.swing.JCheckBox();
        panelCenterRight = new javax.swing.JPanel();
        panelMain = new javax.swing.JPanel();
        panelHeuristics = new javax.swing.JPanel();
        jLabel7 = new javax.swing.JLabel();
        jPanel34 = new javax.swing.JPanel();
        checkBoxTemporaryTable = new javax.swing.JCheckBox();
        checkBoxHavingToWhere = new javax.swing.JCheckBox();
        checkBoxRemoveGroupby = new javax.swing.JCheckBox();
        checkBoxMoveFunction = new javax.swing.JCheckBox();
        checkBoxOrToUnion = new javax.swing.JCheckBox();
        checkBoxAllToSubquery = new javax.swing.JCheckBox();
        checkBoxAnyToSubquery = new javax.swing.JCheckBox();
        checkBoxSomeToSubquery = new javax.swing.JCheckBox();
        checkBoxInToJoin = new javax.swing.JCheckBox();
        checkBoxMoveAtithmetcExpression = new javax.swing.JCheckBox();
        checkBoxRemoveDistinct = new javax.swing.JCheckBox();
        panelInteractive = new javax.swing.JPanel();
        jLabel13 = new javax.swing.JLabel();
        jPanel19 = new javax.swing.JPanel();
        jButton6 = new javax.swing.JButton();
        jLabel15 = new javax.swing.JLabel();
        labelAddRewriteSettings = new javax.swing.JLabel();
        jLabel11 = new javax.swing.JLabel();
        jPanel10 = new javax.swing.JPanel();
        jLabel29 = new javax.swing.JLabel();
        textTimeInterval = new javax.swing.JTextField();
        jLabel30 = new javax.swing.JLabel();
        jPanel25 = new javax.swing.JPanel();
        jLabel31 = new javax.swing.JLabel();
        CashTypeComboBox = new javax.swing.JComboBox();
        jCheckBox1 = new javax.swing.JCheckBox();
        jPanel24 = new javax.swing.JPanel();
        buttonStartAdvisor = new javax.swing.JButton();
        jButton10 = new javax.swing.JButton();
        jPanel18 = new javax.swing.JPanel();
        jLabel14 = new javax.swing.JLabel();
        jButton2 = new javax.swing.JButton();
        jButton7 = new javax.swing.JButton();
        jButton13 = new javax.swing.JButton();
        jPanel28 = new javax.swing.JPanel();
        panelReewriteButtons = new javax.swing.JPanel();
        jButton3 = new javax.swing.JButton();
        checkBoxUseConnection = new javax.swing.JCheckBox();
        jToggleButton1 = new javax.swing.JToggleButton();
        jPanel29 = new javax.swing.JPanel();
        jPanel30 = new javax.swing.JPanel();

        dialogRelatorio.setTitle("Reescritas realizadas na SQL Original");
        dialogRelatorio.setMinimumSize(new java.awt.Dimension(600, 300));
        dialogRelatorio.getContentPane().setLayout(new java.awt.GridLayout(1, 0));

        textAreaRelatorio.setBackground(new java.awt.Color(240, 240, 240));
        textAreaRelatorio.setColumns(20);
        textAreaRelatorio.setEditable(false);
        textAreaRelatorio.setRows(5);
        textAreaRelatorio.setMinimumSize(new java.awt.Dimension(164, 94));
        jScrollPane4.setViewportView(textAreaRelatorio);

        dialogRelatorio.getContentPane().add(jScrollPane4);

        dialogDefaultSettings.setTitle("Reescritas escolhidas para todas as SQLs");
        dialogDefaultSettings.setMinimumSize(new java.awt.Dimension(400, 300));
        dialogDefaultSettings.getContentPane().setLayout(new java.awt.GridLayout(1, 0));

        textAreaDefaultSettings.setBackground(new java.awt.Color(240, 240, 240));
        textAreaDefaultSettings.setColumns(20);
        textAreaDefaultSettings.setEditable(false);
        textAreaDefaultSettings.setRows(5);
        textAreaDefaultSettings.setMinimumSize(new java.awt.Dimension(100, 82));
        textAreaDefaultSettings.setPreferredSize(new java.awt.Dimension(100, 80));
        jScrollPane5.setViewportView(textAreaDefaultSettings);

        dialogDefaultSettings.getContentPane().add(jScrollPane5);

        dialogCustomSettings.setTitle("Reescritas Personalizadas para SQLs");
        dialogCustomSettings.setMinimumSize(new java.awt.Dimension(1000, 430));

        jPanel26.setMinimumSize(new java.awt.Dimension(600, 30));
        jPanel26.setPreferredSize(new java.awt.Dimension(600, 30));
        jPanel26.setLayout(new java.awt.FlowLayout(java.awt.FlowLayout.LEFT));

        jButton1.setText("Excluir");
        jPanel26.add(jButton1);

        dialogCustomSettings.getContentPane().add(jPanel26, java.awt.BorderLayout.PAGE_START);

        jPanel27.setMinimumSize(new java.awt.Dimension(600, 80));
        jPanel27.setPreferredSize(new java.awt.Dimension(600, 80));
        jPanel27.setLayout(new java.awt.GridLayout(5, 3));

        jLabel17.setFont(new java.awt.Font("Tahoma", 1, 11)); // NOI18N
        jLabel17.setText("Legenda");
        jPanel27.add(jLabel17);
        jPanel27.add(jPanel32);
        jPanel27.add(jPanel33);

        jLabel18.setText("H1: Eliminar Tabelas Temporárias");
        jPanel27.add(jLabel18);

        jLabel19.setText("H2: Eliminar Having desnecessário");
        jPanel27.add(jLabel19);

        jLabel20.setText("H3: Eliminar Group by e/ou Having desnecessários");
        jPanel27.add(jLabel20);

        jLabel21.setText("H4: Remover Função assossiada a coluna com índice");
        jPanel27.add(jLabel21);

        jLabel22.setText("H5: Trocar conectivo OR por União de seleções");
        jPanel27.add(jLabel22);

        jLabel23.setText("H6: Substituir operação All por sub-consulta");
        jPanel27.add(jLabel23);

        jLabel24.setText("H7: Substituir operação Any por sub-consulta");
        jPanel27.add(jLabel24);

        jLabel25.setText("H8: Substituir operação Some por sub-consulta");
        jPanel27.add(jLabel25);

        jLabel26.setText("H9: Substituir operação In por junção");
        jPanel27.add(jLabel26);

        jLabel27.setText("H10: Remover Expressão Aritmética de coluna com índice");
        jPanel27.add(jLabel27);

        jLabel28.setText("H11: Remover Distinct desnecessário");
        jPanel27.add(jLabel28);

        dialogCustomSettings.getContentPane().add(jPanel27, java.awt.BorderLayout.PAGE_END);

        tableCustomHeuristics.setModel(new javax.swing.table.DefaultTableModel(
            new Object [][] {
                {null, null, null, null},
                {null, null, null, null},
                {null, null, null, null},
                {null, null, null, null}
            },
            new String [] {
                "SQL", "Title 2", "Title 3", "Title 4"
            }
        ));
        tableCustomHeuristics.setMinimumSize(new java.awt.Dimension(600, 64));
        tableCustomHeuristics.setPreferredSize(new java.awt.Dimension(600, 64));
        jScrollPane6.setViewportView(tableCustomHeuristics);

        dialogCustomSettings.getContentPane().add(jScrollPane6, java.awt.BorderLayout.CENTER);

        dialogExecutionPlan.setTitle("Planos de Execução");
        dialogExecutionPlan.setMinimumSize(new java.awt.Dimension(600, 400));

        textAreaExecutionPlan.setBackground(new java.awt.Color(240, 240, 240));
        textAreaExecutionPlan.setColumns(20);
        textAreaExecutionPlan.setEditable(false);
        textAreaExecutionPlan.setRows(5);
        jScrollPane7.setViewportView(textAreaExecutionPlan);

        dialogExecutionPlan.getContentPane().add(jScrollPane7, java.awt.BorderLayout.CENTER);

        setDefaultCloseOperation(javax.swing.WindowConstants.EXIT_ON_CLOSE);
        setTitle("Interactive Query Tunning");
        setCursor(new java.awt.Cursor(java.awt.Cursor.DEFAULT_CURSOR));
        setName("frameMain"); // NOI18N
        addWindowListener(new java.awt.event.WindowAdapter() {
            public void windowClosed(java.awt.event.WindowEvent evt) {
                formWindowClosed(evt);
            }
            public void windowClosing(java.awt.event.WindowEvent evt) {
                formWindowClosing(evt);
            }
        });

        panelNorth.setLayout(new java.awt.GridLayout(1, 2, 5, 0));

        panelNorthLeft.setLayout(new java.awt.BorderLayout());

        listSqlsFromFile.setSelectionMode(javax.swing.ListSelectionModel.SINGLE_SELECTION);
        listSqlsFromFile.addMouseListener(new java.awt.event.MouseAdapter() {
            public void mouseClicked(java.awt.event.MouseEvent evt) {
                listSqlsFromFileMouseClicked(evt);
            }
        });
        jScrollPane1.setViewportView(listSqlsFromFile);

        panelNorthLeft.add(jScrollPane1, java.awt.BorderLayout.CENTER);

        jPanel9.setLayout(new java.awt.FlowLayout(java.awt.FlowLayout.LEFT));

        jLabel1.setFont(new java.awt.Font("Tahoma", 1, 12)); // NOI18N
        jLabel1.setText("Lista de SQLs ");
        jPanel9.add(jLabel1);

        jToggleButton2.setText("Obter de Arquivo");
        jToggleButton2.addActionListener(new java.awt.event.ActionListener() {
            public void actionPerformed(java.awt.event.ActionEvent evt) {
                jToggleButton2ActionPerformed(evt);
            }
        });
        jPanel9.add(jToggleButton2);

        jButton5.setText("Obter Workload");
        jButton5.addActionListener(new java.awt.event.ActionListener() {
            public void actionPerformed(java.awt.event.ActionEvent evt) {
                jButton5ActionPerformed(evt);
            }
        });
        jPanel9.add(jButton5);

        panelNorthLeft.add(jPanel9, java.awt.BorderLayout.PAGE_START);

        panelNorth.add(panelNorthLeft);

        panelNorthRight.setBorder(javax.swing.BorderFactory.createEtchedBorder());
        panelNorthRight.setLayout(new java.awt.BorderLayout());

        jPanel4.setLayout(new java.awt.FlowLayout(java.awt.FlowLayout.LEFT));

        jLabel2.setFont(new java.awt.Font("Tahoma", 1, 12)); // NOI18N
        jLabel2.setText("Banco de Dados    ");
        jPanel4.add(jLabel2);

        comboBoxBdms.setModel(new javax.swing.DefaultComboBoxModel(new String[] { "PostgreSQL", "SQL Server", "Oracle" }));
        comboBoxBdms.addItemListener(new java.awt.event.ItemListener() {
            public void itemStateChanged(java.awt.event.ItemEvent evt) {
                comboBoxBdmsItemStateChanged(evt);
            }
        });
        comboBoxBdms.addActionListener(new java.awt.event.ActionListener() {
            public void actionPerformed(java.awt.event.ActionEvent evt) {
                comboBoxBdmsActionPerformed(evt);
            }
        });
        jPanel4.add(comboBoxBdms);

        panelNorthRight.add(jPanel4, java.awt.BorderLayout.PAGE_START);

        jPanel8.setLayout(new java.awt.BorderLayout(0, 5));

        jPanel11.setLayout(new java.awt.FlowLayout(java.awt.FlowLayout.LEFT));

        jLabel4.setFont(new java.awt.Font("Tahoma", 1, 12)); // NOI18N
        jLabel4.setText("Configurações");
        jPanel11.add(jLabel4);

        labelNoConnection.setForeground(new java.awt.Color(204, 0, 0));
        labelNoConnection.setText("labelNoConnection");
        jPanel11.add(labelNoConnection);

        jPanel8.add(jPanel11, java.awt.BorderLayout.PAGE_START);

        jPanel12.setLayout(new java.awt.GridLayout(3, 2, 0, 2));

        jPanel22.setLayout(new java.awt.FlowLayout(java.awt.FlowLayout.LEFT, 0, 0));

        jLabel10.setText("Servidor               ");
        jPanel22.add(jLabel10);

        textFieldServer.setColumns(15);
        jPanel22.add(textFieldServer);

        jPanel12.add(jPanel22);

        jPanel13.setLayout(new java.awt.FlowLayout(java.awt.FlowLayout.LEFT, 0, 0));

        jLabel6.setText("Banco de Dados");
        jPanel13.add(jLabel6);

        textFieldDatabase.setColumns(15);
        jPanel13.add(textFieldDatabase);

        jPanel12.add(jPanel13);

        jPanel23.setLayout(new java.awt.FlowLayout(java.awt.FlowLayout.LEFT, 0, 0));

        jLabel12.setText("Porta                    ");
        jPanel23.add(jLabel12);

        textFieldPort.setColumns(15);
        jPanel23.add(textFieldPort);

        jPanel12.add(jPanel23);

        jPanel14.setLayout(new java.awt.FlowLayout(java.awt.FlowLayout.LEFT, 0, 0));

        jLabel8.setText("Usuário                ");
        jPanel14.add(jLabel8);

        textFieldUser.setColumns(15);
        jPanel14.add(textFieldUser);

        jPanel12.add(jPanel14);

        jPanel15.setLayout(new java.awt.FlowLayout(java.awt.FlowLayout.LEFT, 0, 0));

        jLabel9.setText("Senha                  ");
        jPanel15.add(jLabel9);

        textFieldPassword.setColumns(15);
        jPanel15.add(textFieldPassword);

        jPanel12.add(jPanel15);

        checkBoxSavePassword.setText("Salvar senha");
        checkBoxSavePassword.addActionListener(new java.awt.event.ActionListener() {
            public void actionPerformed(java.awt.event.ActionEvent evt) {
                checkBoxSavePasswordActionPerformed(evt);
            }
        });
        jPanel1.add(checkBoxSavePassword);

        jPanel12.add(jPanel1);

        jPanel8.add(jPanel12, java.awt.BorderLayout.CENTER);

        jPanel16.setLayout(new java.awt.FlowLayout(java.awt.FlowLayout.CENTER, 0, 0));
        jPanel8.add(jPanel16, java.awt.BorderLayout.PAGE_END);

        panelNorthRight.add(jPanel8, java.awt.BorderLayout.CENTER);

        jButton4.setText("Testar Conexão");
        jButton4.addActionListener(new java.awt.event.ActionListener() {
            public void actionPerformed(java.awt.event.ActionEvent evt) {
                jButton4ActionPerformed(evt);
            }
        });
        jPanel2.add(jButton4);

        panelNorthRight.add(jPanel2, java.awt.BorderLayout.PAGE_END);

        panelNorth.add(panelNorthRight);

        getContentPane().add(panelNorth, java.awt.BorderLayout.PAGE_START);

        panelCenter.setLayout(new java.awt.GridLayout(1, 2, 5, 0));

        panelCenterLeft.setLayout(new java.awt.GridLayout(2, 1, 5, 0));

        panelCenterLeftTop.setLayout(new java.awt.BorderLayout());

        textAreaSqlIn.setColumns(20);
        textAreaSqlIn.setRows(5);
        jScrollPane2.setViewportView(textAreaSqlIn);

        panelCenterLeftTop.add(jScrollPane2, java.awt.BorderLayout.CENTER);

        jPanel3.setLayout(new java.awt.GridLayout(1, 1));

        jPanel17.setLayout(new java.awt.FlowLayout(java.awt.FlowLayout.LEFT));

        jLabel3.setFont(new java.awt.Font("Tahoma", 1, 11)); // NOI18N
        jLabel3.setText("SQL Original                 ");
        jPanel17.add(jLabel3);

        jButton8.setText("Ver Plano de Execução");
        jButton8.addActionListener(new java.awt.event.ActionListener() {
            public void actionPerformed(java.awt.event.ActionEvent evt) {
                jButton8ActionPerformed(evt);
            }
        });
        jPanel17.add(jButton8);

        buttonExecuteSqlIn.setText("Executar SQL");
        buttonExecuteSqlIn.addActionListener(new java.awt.event.ActionListener() {
            public void actionPerformed(java.awt.event.ActionEvent evt) {
                buttonExecuteSqlInActionPerformed(evt);
            }
        });
        jPanel17.add(buttonExecuteSqlIn);

        labelSqlInResult.setText("Exe. Result");
        jPanel17.add(labelSqlInResult);

        jPanel3.add(jPanel17);

        panelCenterLeftTop.add(jPanel3, java.awt.BorderLayout.PAGE_START);

        checkBoxIdentSQLIn.setText("Identar SQL Reescrita");
        checkBoxIdentSQLIn.addMouseListener(new java.awt.event.MouseAdapter() {
            public void mouseClicked(java.awt.event.MouseEvent evt) {
                checkBoxIdentSQLInMouseClicked(evt);
            }
        });
        jPanel7.add(checkBoxIdentSQLIn);

        panelCenterLeftTop.add(jPanel7, java.awt.BorderLayout.PAGE_END);

        panelCenterLeft.add(panelCenterLeftTop);

        panelCenterLeftBottom.setLayout(new java.awt.BorderLayout());

        jPanel6.setLayout(new java.awt.GridLayout(2, 1));

        labelMessengeRewrite.setFont(new java.awt.Font("Tahoma", 1, 11)); // NOI18N
        labelMessengeRewrite.setForeground(new java.awt.Color(0, 153, 0));
        labelMessengeRewrite.setText("Msg reescrita");
        jPanel21.add(labelMessengeRewrite);

        labelRewriteError.setFont(new java.awt.Font("Tahoma", 1, 11)); // NOI18N
        labelRewriteError.setForeground(new java.awt.Color(204, 0, 0));
        labelRewriteError.setText("Rewriting Error");
        jPanel21.add(labelRewriteError);

        labelExecutingRewrite.setText(" Executing Rewrite");
        jPanel21.add(labelExecutingRewrite);

        jPanel6.add(jPanel21);

        jPanel20.setLayout(new java.awt.FlowLayout(java.awt.FlowLayout.LEFT));

        jLabel5.setFont(new java.awt.Font("Tahoma", 1, 11)); // NOI18N
        jLabel5.setText("SQL Reescrita              ");
        jPanel20.add(jLabel5);

        jButton9.setText("Ver Plano de Execução");
        jButton9.addActionListener(new java.awt.event.ActionListener() {
            public void actionPerformed(java.awt.event.ActionEvent evt) {
                jButton9ActionPerformed(evt);
            }
        });
        jPanel20.add(jButton9);

        buttonExecuteSqlOut.setText("Executar SQL");
        buttonExecuteSqlOut.addActionListener(new java.awt.event.ActionListener() {
            public void actionPerformed(java.awt.event.ActionEvent evt) {
                buttonExecuteSqlOutActionPerformed(evt);
            }
        });
        jPanel20.add(buttonExecuteSqlOut);

        labelSqlOutResult.setText("Exe. Result");
        jPanel20.add(labelSqlOutResult);

        jPanel6.add(jPanel20);

        panelCenterLeftBottom.add(jPanel6, java.awt.BorderLayout.PAGE_START);

        textAreaSqlOut.setColumns(20);
        textAreaSqlOut.setRows(5);
        jScrollPane3.setViewportView(textAreaSqlOut);

        panelCenterLeftBottom.add(jScrollPane3, java.awt.BorderLayout.CENTER);

        checkBoxIdentSQLOut.setText("Identar SQL Reescrita");
        checkBoxIdentSQLOut.addMouseListener(new java.awt.event.MouseAdapter() {
            public void mouseClicked(java.awt.event.MouseEvent evt) {
                checkBoxIdentSQLOutMouseClicked(evt);
            }
        });
        checkBoxIdentSQLOut.addActionListener(new java.awt.event.ActionListener() {
            public void actionPerformed(java.awt.event.ActionEvent evt) {
                checkBoxIdentSQLOutActionPerformed(evt);
            }
        });
        jPanel5.add(checkBoxIdentSQLOut);

        panelCenterLeftBottom.add(jPanel5, java.awt.BorderLayout.PAGE_END);

        panelCenterLeft.add(panelCenterLeftBottom);

        panelCenter.add(panelCenterLeft);

        panelCenterRight.setLayout(new java.awt.BorderLayout());

        panelMain.setLayout(new java.awt.GridLayout(2, 1));

        panelHeuristics.setLayout(new java.awt.GridLayout(7, 2));

        jLabel7.setFont(new java.awt.Font("Tahoma", 1, 11)); // NOI18N
        jLabel7.setText("Heurísticas para Sintonia de Cláusulas SQL");
        panelHeuristics.add(jLabel7);

        jPanel34.setLayout(new java.awt.FlowLayout(java.awt.FlowLayout.LEFT));
        panelHeuristics.add(jPanel34);

        checkBoxTemporaryTable.setText("Eliminar Tabelas Temporárias");
        panelHeuristics.add(checkBoxTemporaryTable);

        checkBoxHavingToWhere.setText("Eliminar Having desnecessário");
        checkBoxHavingToWhere.addActionListener(new java.awt.event.ActionListener() {
            public void actionPerformed(java.awt.event.ActionEvent evt) {
                checkBoxHavingToWhereActionPerformed(evt);
            }
        });
        panelHeuristics.add(checkBoxHavingToWhere);

        checkBoxRemoveGroupby.setText("Eliminar Group by desnecessário");
        panelHeuristics.add(checkBoxRemoveGroupby);

        checkBoxMoveFunction.setText("Remover coluna com índice de  Função");
        checkBoxMoveFunction.addActionListener(new java.awt.event.ActionListener() {
            public void actionPerformed(java.awt.event.ActionEvent evt) {
                checkBoxMoveFunctionActionPerformed(evt);
            }
        });
        panelHeuristics.add(checkBoxMoveFunction);

        checkBoxOrToUnion.setText("Trocar conectivo OR por União de seleções");
        panelHeuristics.add(checkBoxOrToUnion);

        checkBoxAllToSubquery.setText("Substituir operação All por sub-consulta");
        panelHeuristics.add(checkBoxAllToSubquery);

        checkBoxAnyToSubquery.setText("Substituir operação Any por sub-consulta");
        panelHeuristics.add(checkBoxAnyToSubquery);

        checkBoxSomeToSubquery.setText("Substituir operação Some por sub-consulta");
        panelHeuristics.add(checkBoxSomeToSubquery);

        checkBoxInToJoin.setText("Substituir operação In por junção");
        panelHeuristics.add(checkBoxInToJoin);

        checkBoxMoveAtithmetcExpression.setText("Remover coluna com índice de Expressão Aritmética");
        checkBoxMoveAtithmetcExpression.addActionListener(new java.awt.event.ActionListener() {
            public void actionPerformed(java.awt.event.ActionEvent evt) {
                checkBoxMoveAtithmetcExpressionActionPerformed(evt);
            }
        });
        panelHeuristics.add(checkBoxMoveAtithmetcExpression);

        checkBoxRemoveDistinct.setText("Remover Distinct desnecessário");
        panelHeuristics.add(checkBoxRemoveDistinct);

        panelMain.add(panelHeuristics);

        panelInteractive.setBorder(javax.swing.BorderFactory.createEtchedBorder());
        panelInteractive.setLayout(new java.awt.GridLayout(7, 0));

        jLabel13.setFont(new java.awt.Font("Tahoma", 1, 11)); // NOI18N
        jLabel13.setText("Definir as Heurísticas Selecionadas como Sintonia Padrão para a SQL Selecionada");
        jLabel13.setMinimumSize(new java.awt.Dimension(329, 12));
        jLabel13.setPreferredSize(new java.awt.Dimension(329, 12));
        panelInteractive.add(jLabel13);

        jPanel19.setBorder(javax.swing.BorderFactory.createMatteBorder(0, 0, 1, 0, new java.awt.Color(153, 153, 153)));
        jPanel19.setLayout(new java.awt.FlowLayout(java.awt.FlowLayout.LEFT, 5, 0));

        jButton6.setText("Adicionar Definição de Sintonia");
        jButton6.setToolTipText("Define as heurísticas selecionadas como as que apenas serão utilizadas na reescrita da SQL Original selecionada.");
        jButton6.addActionListener(new java.awt.event.ActionListener() {
            public void actionPerformed(java.awt.event.ActionEvent evt) {
                jButton6ActionPerformed(evt);
            }
        });
        jPanel19.add(jButton6);

        jLabel15.setFont(new java.awt.Font("Tahoma", 1, 11)); // NOI18N
        jLabel15.setForeground(new java.awt.Color(0, 51, 255));
        jLabel15.setText("Editar Reescritas Personalizadas");
        jLabel15.setCursor(new java.awt.Cursor(java.awt.Cursor.DEFAULT_CURSOR));
        jLabel15.addMouseListener(new java.awt.event.MouseAdapter() {
            public void mouseClicked(java.awt.event.MouseEvent evt) {
                jLabel15MouseClicked(evt);
            }
        });
        jPanel19.add(jLabel15);

        labelAddRewriteSettings.setFont(new java.awt.Font("Tahoma", 1, 11)); // NOI18N
        labelAddRewriteSettings.setForeground(new java.awt.Color(0, 153, 0));
        labelAddRewriteSettings.setText("Msg add");
        jPanel19.add(labelAddRewriteSettings);

        panelInteractive.add(jPanel19);

        jLabel11.setFont(new java.awt.Font("Tahoma", 1, 11)); // NOI18N
        jLabel11.setText("Advisor");
        panelInteractive.add(jLabel11);

        jPanel10.setLayout(new java.awt.FlowLayout(java.awt.FlowLayout.LEFT));

        jLabel29.setText("Intervalo de Tempo entre as Sessões de Sintonia");
        jPanel10.add(jLabel29);
        jLabel29.getAccessibleContext().setAccessibleDescription("");

        textTimeInterval.setColumns(15);
        jPanel10.add(textTimeInterval);

        jLabel30.setText("(ms)         ");
        jPanel10.add(jLabel30);

        panelInteractive.add(jPanel10);

        jPanel25.setLayout(new java.awt.FlowLayout(java.awt.FlowLayout.LEFT, 5, 0));

        jLabel31.setText("Tipo Cash");
        jPanel25.add(jLabel31);

        CashTypeComboBox.setModel(new javax.swing.DefaultComboBoxModel(new String[] { "Sem cash", "Cash de Heurísticas", "Cash de SQLs Reescritas" }));
        jPanel25.add(CashTypeComboBox);

        jCheckBox1.setText("Executar em segundo plano");
        jPanel25.add(jCheckBox1);

        panelInteractive.add(jPanel25);

        jPanel24.setBorder(javax.swing.BorderFactory.createMatteBorder(0, 0, 1, 0, new java.awt.Color(153, 153, 153)));
        jPanel24.setLayout(new java.awt.FlowLayout(java.awt.FlowLayout.CENTER, 5, 1));

        buttonStartAdvisor.setText("Iniciar Advisor");
        buttonStartAdvisor.setToolTipText("Define as heurísticas selecionadas como as que apenas serão utilizadas na reescrita de todas as SQLs.");
        buttonStartAdvisor.addActionListener(new java.awt.event.ActionListener() {
            public void actionPerformed(java.awt.event.ActionEvent evt) {
                buttonStartAdvisorActionPerformed(evt);
            }
        });
        jPanel24.add(buttonStartAdvisor);

        jButton10.setText("Limpar Cash");
        jButton10.addActionListener(new java.awt.event.ActionListener() {
            public void actionPerformed(java.awt.event.ActionEvent evt) {
                jButton10ActionPerformed(evt);
            }
        });
        jPanel24.add(jButton10);

        panelInteractive.add(jPanel24);

        jPanel18.setLayout(new java.awt.FlowLayout(java.awt.FlowLayout.LEFT));

        jLabel14.setFont(new java.awt.Font("Tahoma", 1, 11)); // NOI18N
        jLabel14.setText("Workload");
        jPanel18.add(jLabel14);

        jButton2.setText("Visualizar Workload");
        jButton2.addActionListener(new java.awt.event.ActionListener() {
            public void actionPerformed(java.awt.event.ActionEvent evt) {
                jButton2ActionPerformed(evt);
            }
        });
        jPanel18.add(jButton2);

        jButton7.setText("Limpar Workload");
        jButton7.addActionListener(new java.awt.event.ActionListener() {
            public void actionPerformed(java.awt.event.ActionEvent evt) {
                jButton7ActionPerformed(evt);
            }
        });
        jPanel18.add(jButton7);

        jButton13.setText("Sugestões de Sintonia");
        jButton13.addActionListener(new java.awt.event.ActionListener() {
            public void actionPerformed(java.awt.event.ActionEvent evt) {
                jButton13ActionPerformed(evt);
            }
        });
        jPanel18.add(jButton13);

        panelInteractive.add(jPanel18);

        panelMain.add(panelInteractive);

        panelCenterRight.add(panelMain, java.awt.BorderLayout.CENTER);

        jPanel28.setLayout(new java.awt.GridLayout(1, 0));

        panelReewriteButtons.setLayout(new javax.swing.BoxLayout(panelReewriteButtons, javax.swing.BoxLayout.LINE_AXIS));

        jButton3.setText("Reescrever");
        jButton3.addActionListener(new java.awt.event.ActionListener() {
            public void actionPerformed(java.awt.event.ActionEvent evt) {
                jButton3ActionPerformed(evt);
            }
        });
        panelReewriteButtons.add(jButton3);

        checkBoxUseConnection.setSelected(true);
        checkBoxUseConnection.setText("Utilizar heurísticas baseadas em estatísticas");
        checkBoxUseConnection.addMouseListener(new java.awt.event.MouseAdapter() {
            public void mouseClicked(java.awt.event.MouseEvent evt) {
                checkBoxUseConnectionMouseClicked(evt);
            }
        });
        checkBoxUseConnection.addActionListener(new java.awt.event.ActionListener() {
            public void actionPerformed(java.awt.event.ActionEvent evt) {
                checkBoxUseConnectionActionPerformed(evt);
            }
        });
        panelReewriteButtons.add(checkBoxUseConnection);

        jToggleButton1.setText("Exibir Relatório de Sintonia");
        jToggleButton1.addActionListener(new java.awt.event.ActionListener() {
            public void actionPerformed(java.awt.event.ActionEvent evt) {
                jToggleButton1ActionPerformed(evt);
            }
        });
        panelReewriteButtons.add(jToggleButton1);

        jPanel28.add(panelReewriteButtons);

        panelCenterRight.add(jPanel28, java.awt.BorderLayout.PAGE_START);
        panelCenterRight.add(jPanel29, java.awt.BorderLayout.LINE_START);
        panelCenterRight.add(jPanel30, java.awt.BorderLayout.LINE_END);

        panelCenter.add(panelCenterRight);

        getContentPane().add(panelCenter, java.awt.BorderLayout.CENTER);

        pack();
    }// </editor-fold>//GEN-END:initComponents

    private void jToggleButton2ActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_jToggleButton2ActionPerformed
        // TODO add your handling code here:
        JFileChooser fc = new JFileChooser();

        // restringe a amostra a diretorios apenas
        fc.setFileSelectionMode(JFileChooser.FILES_ONLY);

        int res = fc.showOpenDialog(null);

        if (res == JFileChooser.APPROVE_OPTION) {
            File diretorio = fc.getSelectedFile();
            String[] sqlFile = this.getSqlFile(diretorio.getAbsolutePath());
            if (sqlFile == null) {
                JOptionPane.showMessageDialog(null, "Erro ao selecionar o arquivo!");
            } else {
                listSqlsFromFile.setListData(sqlFile);
            }
        }
    }//GEN-LAST:event_jToggleButton2ActionPerformed

    private String[] getSqlFile(String fileName) {
        if ((fileName == null) || (fileName.isEmpty())) {
            return null;
        }

        File f = new File(fileName);

        if (!f.exists()) {
            return null;
        }

        String lineIn;
        Vector linesOut = new Vector();
        try {
            BufferedReader in = new BufferedReader(new FileReader(f));
            while ((lineIn = in.readLine()) != null) {
                if (!lineIn.equals("")) {
                    linesOut.add(lineIn);
                }
            }
            in.close();
        } catch (Exception e) {
            return null;
        }

        String[] strings = new String[linesOut.size()];
        for (int i = 0; i < linesOut.size(); i++) {
            strings[i] = (String) linesOut.get(i);
        }

        return strings;
    }

    private void buttonExecuteSqlOutActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_buttonExecuteSqlOutActionPerformed
        // TODO add your handling code here:
        String sqlOut = textAreaSqlOut.getText();
        if (!sqlOut.equals("")) {
            if (this.buttonExecuteSqlOut.getText().equals("Executar SQL")) {
                int dbmsSelected = this.getDbmsSelected();
                String server = this.textFieldServer.getText();
                String port = textFieldPort.getText();
                String database = textFieldDatabase.getText();
                String user = this.textFieldUser.getText();
                String password = this.textFieldPassword.getText();
                Dbms dbms = new Dbms(dbmsSelected, server, port, database, user, password);

                labelSqlOutResult.setText("Executando ...");
                this.buttonExecuteSqlOut.setText("  Cancelar  ");

                this.sqlOutThread = new ExecuteQuery(dbms, sqlOut, this.labelSqlOutResult, this.buttonExecuteSqlOut);
                this.sqlOutThread.start();
            } else {
                this.labelSqlOutResult.setText("");
                this.buttonExecuteSqlOut.setText("Executar SQL");
                this.sqlOutThread.stop();
            }
        }
    }//GEN-LAST:event_buttonExecuteSqlOutActionPerformed

    private void listSqlsFromFileMouseClicked(java.awt.event.MouseEvent evt) {//GEN-FIRST:event_listSqlsFromFileMouseClicked
        // TODO add your handling code here:
        String sqlIn = (String) listSqlsFromFile.getSelectedValue();
        if (sqlIn != null) {
            if (checkBoxIdentSQLIn.isSelected()) {
                sqlIn = Indenter.ident(sqlIn);
            }
            textAreaSqlIn.setText(sqlIn);
        }

        this.textAreaSqlOut.setText("");
        this.labelSqlInResult.setText("");
        this.labelSqlOutResult.setText("");
        this.labelRewriteError.setText("");
        this.labelMessengeRewrite.setText("");
        this.labelAddRewriteSettings.setText("");
//        labelAddRewriteSettingsAll.setText("");
//        this.labelMsgHeuristicApllied.setText("");
        this.setCheckBoxsAsPlain();
        this.setCheckBoxsAsSelected();
    }//GEN-LAST:event_listSqlsFromFileMouseClicked

    private void checkBoxHavingToWhereActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_checkBoxHavingToWhereActionPerformed
        // TODO add your handling code here:
    }//GEN-LAST:event_checkBoxHavingToWhereActionPerformed

    private void jButton3ActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_jButton3ActionPerformed
        // TODO add your handling code here:
        String sqlIn = textAreaSqlIn.getText();
        labelExecutingRewrite.setText("        Executando reescrita ...");
        labelRewriteError.setText("");
        labelMessengeRewrite.setText("");
        textAreaSqlOut.setText("");
        labelSqlOutResult.setText("");
        labelAddRewriteSettings.setText("");
//        labelAddRewriteSettingsAll.setText("");
        if (!sqlIn.isEmpty()) {
            int dbmsSelected = this.getDbmsSelected();
            if (checkBoxUseConnection.isSelected()) {
                String server = this.textFieldServer.getText();
                String port = textFieldPort.getText();
                String database = textFieldDatabase.getText();
                String user = this.textFieldUser.getText();
                String password = this.textFieldPassword.getText();
                Dbms dbms = new Dbms(dbmsSelected, server, port, database, user, password);

                boolean result = ConnectionDbms.testConnection(dbms);
                if (!result) {
                    agentRewriter = new AgentRewriter(dbmsSelected);
                    labelNoConnection.setText("A conexão como o banco de dados falhou! Alguma heurísticas não puderam ser executadas.");
                } else {
                    agentRewriter = new AgentRewriter(dbms);
                    labelNoConnection.setText("");
                }
            } else {
                agentRewriter = new AgentRewriter(dbmsSelected);
                //labelNoConnection.setText("As heurísticas baseadas em estatísticas não foram executadas!");
            }

            HeuristicsSelected heuristicsSelect = new HeuristicsSelected();
            this.setHeuristicsSelected(heuristicsSelect);
            String sqlOut;
            try {
                sqlOut = agentRewriter.analyseStatement(textAreaSqlIn.getText(), heuristicsSelect);
                if (agentRewriter.isRewrited()) {
                    if (checkBoxIdentSQLOut.isSelected()) {
                        sqlOut = Indenter.ident(sqlOut);
                    }
                    textAreaSqlOut.setText(sqlOut);
                    String messenge;
                    int count = agentRewriter.getCount();
                    if (count == 1) {
                        messenge = "        Foi realizada 1 reescrita! Tempo = " + (long) agentRewriter.getTimeMillis() + " ms";
                    } else {
                        messenge = "        Foram realizadas " + count + " reescritas! Tempo = " + (long) agentRewriter.getTimeMillis() + " ms";
                    }
                    labelMessengeRewrite.setText(messenge);
//                    labelMsgHeuristicApllied.setText("As heurísticas que puderam ser aplicadas foram destacadas em negrito");
                } else {
                    labelRewriteError.setText("        Nenhuma reescrita encontrada para a SQL! Tempo = " + (long) agentRewriter.getTimeMillis() + " ms");
                }

                this.setCheckBoxsAsPlain();
                this.setCheckBoxsAsHeuristicsExecuted(heuristicsSelect);
            } catch (ClassNotFoundException ex) {
                JOptionPane.showMessageDialog(null, ex.getMessage(), "Erro", JOptionPane.ERROR_MESSAGE);
                //Logger.getLogger(AdvisorGUI.class.getName()).log(Level.SEVERE, null, ex);
            } catch (SQLException ex) {
                JOptionPane.showMessageDialog(null, ex.getMessage(), "Erro", JOptionPane.ERROR_MESSAGE);
                //Logger.getLogger(AdvisorGUI.class.getName()).log(Level.SEVERE, null, ex);
            } catch (SqlInputException ex) {
                JOptionPane.showMessageDialog(null, ex.getMessage(), "Erro", JOptionPane.ERROR_MESSAGE);
                System.out.println("Erro3:" + ex.getMessage());
            } catch (java.text.ParseException ex) {
                JOptionPane.showMessageDialog(null, ex.getMessage(), "Erro", JOptionPane.ERROR_MESSAGE);
                //Logger.getLogger(AdvisorGUI.class.getName()).log(Level.SEVERE, null, ex);
            } catch (ParseException ex) {
                JOptionPane.showMessageDialog(null, ex.getMessage(), "Erro", JOptionPane.ERROR_MESSAGE);
                //Logger.getLogger(AdvisorGUI.class.getName()).log(Level.SEVERE, null, ex);
            } catch (DbmsException ex) {
                JOptionPane.showMessageDialog(null, ex.getMessage(), "Erro", JOptionPane.ERROR_MESSAGE);
                //Logger.getLogger(AdvisorGUI.class.getName()).log(Level.SEVERE, null, ex);
            }
        }
        this.labelExecutingRewrite.setText("");
    }//GEN-LAST:event_jButton3ActionPerformed

    private void buttonExecuteSqlInActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_buttonExecuteSqlInActionPerformed
        // TODO add your handling code here:
        String sqlIn = this.textAreaSqlIn.getText();
        if (!sqlIn.equals("")) {
            if (this.buttonExecuteSqlIn.getText().equals("Executar SQL")) {
                int dbmsSelected = this.getDbmsSelected();
                String server = this.textFieldServer.getText();
                String port = textFieldPort.getText();
                String database = textFieldDatabase.getText();
                String user = this.textFieldUser.getText();
                String password = this.textFieldPassword.getText();
                Dbms dbms = new Dbms(dbmsSelected, server, port, database, user, password);

                labelSqlInResult.setText("Executando ...");
                this.buttonExecuteSqlIn.setText("  Cancelar  ");

                this.sqlInThread = new ExecuteQuery(dbms, sqlIn, this.labelSqlInResult, this.buttonExecuteSqlIn);
                this.sqlInThread.start();
            } else {
                this.labelSqlInResult.setText("");
                this.buttonExecuteSqlIn.setText("Executar SQL");
                this.sqlInThread.stop();
            }
        }
    }//GEN-LAST:event_buttonExecuteSqlInActionPerformed

    private void formWindowClosed(java.awt.event.WindowEvent evt) {//GEN-FIRST:event_formWindowClosed
        // TODO add your handling code here:
    }//GEN-LAST:event_formWindowClosed

    private void formWindowClosing(java.awt.event.WindowEvent evt) {//GEN-FIRST:event_formWindowClosing
        this.saveSelectedDatabase();
        this.saveDatabaseSettings();
        this.saveCheckBoxState(fileNameStateCheckBoxSavePassword, this.checkBoxSavePassword.isSelected());
        this.saveCheckBoxState(fileNameStateCheckBoxIdentSqlOut, this.checkBoxIdentSQLOut.isSelected());
        this.saveCheckBoxState(fileNameStateCheckBoxIdentSqlIn, this.checkBoxIdentSQLIn.isSelected());
        //
    }//GEN-LAST:event_formWindowClosing

    private void checkBoxSavePasswordActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_checkBoxSavePasswordActionPerformed
        // TODO add your handling code here:
    }//GEN-LAST:event_checkBoxSavePasswordActionPerformed

    private void comboBoxBdmsItemStateChanged(java.awt.event.ItemEvent evt) {//GEN-FIRST:event_comboBoxBdmsItemStateChanged
        // TODO add your handling code here:
        this.getDatabaseSettings();
    }//GEN-LAST:event_comboBoxBdmsItemStateChanged

    private void comboBoxBdmsActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_comboBoxBdmsActionPerformed
        // TODO add your handling code here:
    }//GEN-LAST:event_comboBoxBdmsActionPerformed

    private void jToggleButton1ActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_jToggleButton1ActionPerformed
        // TODO add your handling code here:
        if (agentRewriter != null && agentRewriter.isRewrited()) {
            StringBuilder texto = new StringBuilder("RELATÓRIO DE REESCRITAS\n\n");
            Vector transformationList = (Vector) agentRewriter.getTransformationList();

            for (Object object : transformationList) {
                Transformation t = (Transformation) object;
                texto.append(t.toString()).append("\n\n");
            }
            textAreaRelatorio.setText(texto.toString());
            Dimension paneSize = dialogRelatorio.getSize();
            Dimension screenSize = dialogRelatorio.getToolkit().getScreenSize();
            dialogRelatorio.setLocation((screenSize.width - paneSize.width) / 2, (screenSize.height - paneSize.height) / 2);
            dialogRelatorio.setVisible(true);
        }
    }//GEN-LAST:event_jToggleButton1ActionPerformed

    private void jButton4ActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_jButton4ActionPerformed
        if (textFieldServer.getText().trim().equals("")) {
            JOptionPane.showMessageDialog(null, "Digite o endereço do servidor!", "Erro", JOptionPane.ERROR_MESSAGE);
        } else if (textFieldPort.getText().trim().equals("")) {
            JOptionPane.showMessageDialog(null, "Digite o número da porta!", "Erro", JOptionPane.ERROR_MESSAGE);
        } else if (textFieldPort.getText().trim().equals("")) {
            JOptionPane.showMessageDialog(null, "Digite o nome do usuário!", "Erro", JOptionPane.ERROR_MESSAGE);
        } else {
            int dbmsSelected = this.getDbmsSelected();
            String server = this.textFieldServer.getText();
            String port = textFieldPort.getText();
            String database = textFieldDatabase.getText();
            String user = this.textFieldUser.getText();
            String password = this.textFieldPassword.getText();
            Dbms dbms = new Dbms(dbmsSelected, server, port, database, user, password);
            boolean result = ConnectionDbms.testConnection(dbms);
            if (result) {
                JOptionPane.showMessageDialog(null, "Conexão bem sucedida!", "", JOptionPane.OK_OPTION);
                this.saveDatabaseSettings();
            } else {
                String message = ConnectionDbms.message;
                JOptionPane.showMessageDialog(null, message, "Erro", JOptionPane.ERROR_MESSAGE);
            }
        }
    }//GEN-LAST:event_jButton4ActionPerformed

    private void checkBoxIdentSQLOutActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_checkBoxIdentSQLOutActionPerformed
        // TODO add your handling code here:
    }//GEN-LAST:event_checkBoxIdentSQLOutActionPerformed

    private void checkBoxIdentSQLOutMouseClicked(java.awt.event.MouseEvent evt) {//GEN-FIRST:event_checkBoxIdentSQLOutMouseClicked
        String text;
        if (checkBoxIdentSQLOut.isSelected()) {
            text = Indenter.ident(textAreaSqlOut.getText());
        } else {
            text = textAreaSqlOut.getText();
            text = Indenter.unindent(text);
        }
        textAreaSqlOut.setText(text);
    }//GEN-LAST:event_checkBoxIdentSQLOutMouseClicked

    private void checkBoxIdentSQLInMouseClicked(java.awt.event.MouseEvent evt) {//GEN-FIRST:event_checkBoxIdentSQLInMouseClicked
        String text;
        if (checkBoxIdentSQLIn.isSelected()) {
            text = Indenter.ident(textAreaSqlIn.getText());
        } else {
            text = textAreaSqlIn.getText();
            text = Indenter.unindent(text);
        }
        textAreaSqlIn.setText(text);
    }//GEN-LAST:event_checkBoxIdentSQLInMouseClicked

    private void jButton5ActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_jButton5ActionPerformed
        if (textFieldServer.getText().trim().equals("")) {
            JOptionPane.showMessageDialog(null, "Digite o endereço do servidor!", "Erro", JOptionPane.ERROR_MESSAGE);
        } else if (textFieldPort.getText().trim().equals("")) {
            JOptionPane.showMessageDialog(null, "Digite o número da porta!", "Erro", JOptionPane.ERROR_MESSAGE);
        } else if (textFieldPort.getText().trim().equals("")) {
            JOptionPane.showMessageDialog(null, "Digite o nome do usuário!", "Erro", JOptionPane.ERROR_MESSAGE);
        } else {
            int dbmsSelected = this.getDbmsSelected();
            String server = this.textFieldServer.getText();
            String port = textFieldPort.getText();
            String database = textFieldDatabase.getText();
            String user = this.textFieldUser.getText();
            String password = this.textFieldPassword.getText();
            Dbms dbms = new Dbms(dbmsSelected, server, port, database, user, password);
            boolean result = ConnectionDbms.testConnection(dbms);
            if (result) {
                ArrayList workloadFile = new ArrayList();
                try {
                    File file = new File(fileWorkloadFile);
                    FileReader fileReader = new FileReader(file);
                    BufferedReader bufferedReader = new BufferedReader(fileReader);
                    String line;
                    while ((line = bufferedReader.readLine()) != null) {
                        workloadFile.add(line);
                    }
                    fileReader.close();
                    bufferedReader.close();
                } catch (IOException e) {
                    JOptionPane.showMessageDialog(null, e.getMessage(), "Erro", JOptionPane.ERROR_MESSAGE);
                    //e.printStackTrace();
                }

                String[] strings = new String[workloadFile.size()];
                for (int i = 0; i < workloadFile.size(); i++) {
                    strings[i] = (String) workloadFile.get(i);
                }

                listSqlsFromFile.setListData(strings);
                this.saveDatabaseSettings();
            } else {
                String message = ConnectionDbms.message;
                JOptionPane.showMessageDialog(null, message, "Erro", JOptionPane.ERROR_MESSAGE);
            }
        }
    }//GEN-LAST:event_jButton5ActionPerformed

    private void checkBoxUseConnectionMouseClicked(java.awt.event.MouseEvent evt) {//GEN-FIRST:event_checkBoxUseConnectionMouseClicked
        // TODO add your handling code here:
        if (checkBoxUseConnection.isSelected()) {
            checkBoxMoveFunction.setEnabled(true);
            checkBoxMoveFunction.setSelected(true);
            checkBoxOrToUnion.setEnabled(true);
            checkBoxOrToUnion.setSelected(true);
            checkBoxMoveAtithmetcExpression.setEnabled(true);
            checkBoxMoveAtithmetcExpression.setSelected(true);
            checkBoxRemoveGroupby.setEnabled(true);
            checkBoxRemoveGroupby.setSelected(true);
            checkBoxRemoveDistinct.setEnabled(true);
            checkBoxRemoveDistinct.setSelected(true);
        } else {
            checkBoxMoveFunction.setSelected(false);
            checkBoxMoveFunction.setEnabled(false);
            checkBoxOrToUnion.setSelected(false);
            checkBoxOrToUnion.setEnabled(false);
            checkBoxMoveAtithmetcExpression.setSelected(false);
            checkBoxMoveAtithmetcExpression.setEnabled(false);
            checkBoxRemoveGroupby.setSelected(false);
            checkBoxRemoveGroupby.setEnabled(false);
            checkBoxRemoveDistinct.setSelected(false);
            checkBoxRemoveDistinct.setEnabled(false);
        }
    }//GEN-LAST:event_checkBoxUseConnectionMouseClicked

    private void jButton6ActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_jButton6ActionPerformed
        String sql = textAreaSqlIn.getText();
        if (!sql.equals("")) {
            try {
                HeuristicsSelected heuristicsSelected = new HeuristicsSelected();
                this.setHeuristicsSelected(heuristicsSelected);
                AgentRewriter.addHeuristicsInCash(sql, null, heuristicsSelected);
                labelAddRewriteSettings.setText("Reescrita adicionada!");
            } catch (FileNotFoundException ex) {
                JOptionPane.showMessageDialog(null, ex.getMessage(), "Erro", JOptionPane.ERROR_MESSAGE);
            } catch (IOException ex) {
                JOptionPane.showMessageDialog(null, ex.getMessage(), "Erro", JOptionPane.ERROR_MESSAGE);
            } catch (SqlInputException ex) {
                JOptionPane.showMessageDialog(null, ex.getMessage(), "Erro", JOptionPane.ERROR_MESSAGE);
            } catch (HeuristicsSelectedException ex) {
                JOptionPane.showMessageDialog(null, ex.getMessage(), "Erro", JOptionPane.ERROR_MESSAGE);
            }
        } else {
            String message = "Uma SQL deve ser escolhida ou digitada no campo 'SQL Original'";
            JOptionPane.showMessageDialog(null, message, "Erro", JOptionPane.ERROR_MESSAGE);
        }

    }//GEN-LAST:event_jButton6ActionPerformed

    private void jLabel15MouseClicked(java.awt.event.MouseEvent evt) {//GEN-FIRST:event_jLabel15MouseClicked
        String[] titles = new String[]{
            "SQL", "H1", "H2", "H3", "H4", "H5", "H6", "H7", "H8", "H9", "H10", "H11",};
        Object[][] rows = null;

        ArrayList list = null;
        try {
            list = AgentRewriter.getHeuristicsFromCash();
        } catch (FileNotFoundException ex) {
            JOptionPane.showMessageDialog(null, ex.getMessage(), "Erro", JOptionPane.ERROR_MESSAGE);
            //Logger.getLogger(AdvisorGUI.class.getName()).log(Level.SEVERE, null, ex);
        } catch (IOException ex) {
            JOptionPane.showMessageDialog(null, ex.getMessage(), "Erro", JOptionPane.ERROR_MESSAGE);
            //Logger.getLogger(AdvisorGUI.class.getName()).log(Level.SEVERE, null, ex);
        }
        if (list != null) {
            int count = list.size();
            rows = new Object[count][12];

            for (int i = 0; i < count; i++) {
                HeuristicsForSql heuristicsForSql = (HeuristicsForSql) list.get(i);
                HeuristicsSelected heuristicsSelected = heuristicsForSql.getHeuristicsSelected();
                rows[i][0] = heuristicsForSql.getSql();
                rows[i][1] = Convertion.trueOrFalseToYesOrNo(heuristicsSelected.isTemporaryTableToSubQuerySelected());
                rows[i][2] = Convertion.trueOrFalseToYesOrNo(heuristicsSelected.isHavingToWhereSelected());
                rows[i][3] = Convertion.trueOrFalseToYesOrNo(heuristicsSelected.isRemoveGroupbySelected());
                rows[i][4] = Convertion.trueOrFalseToYesOrNo(heuristicsSelected.isMoveFunctionSelected());
                rows[i][5] = Convertion.trueOrFalseToYesOrNo(heuristicsSelected.isOrToUnionSelected());
                rows[i][6] = Convertion.trueOrFalseToYesOrNo(heuristicsSelected.isAllToSubquerySelected());
                rows[i][7] = Convertion.trueOrFalseToYesOrNo(heuristicsSelected.isAnyToSubquerySelected());
                rows[i][8] = Convertion.trueOrFalseToYesOrNo(heuristicsSelected.isSomeToSubquerySelected());
                rows[i][9] = Convertion.trueOrFalseToYesOrNo(heuristicsSelected.isInToJoinSelected());
                rows[i][10] = Convertion.trueOrFalseToYesOrNo(heuristicsSelected.isMoveAtithmetcExpressionSelected());
                rows[i][11] = Convertion.trueOrFalseToYesOrNo(heuristicsSelected.isRemoveDistinctSelected());
            }
        }

        tableCustomHeuristics.setModel(new DefaultTableModel(rows, titles));

        Dimension paneSize = dialogCustomSettings.getSize();
        Dimension screenSize = dialogCustomSettings.getToolkit().getScreenSize();
        dialogCustomSettings.setLocation((screenSize.width - paneSize.width) / 2, (screenSize.height - paneSize.height) / 2);
        dialogCustomSettings.setVisible(true);
    }//GEN-LAST:event_jLabel15MouseClicked

    private void jButton8ActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_jButton8ActionPerformed
        StringBuilder text = new StringBuilder();
        String sqlIn = textAreaSqlIn.getText();
        if (!sqlIn.equals("")) {
            int dbmsSelected = this.getDbmsSelected();
            String server = this.textFieldServer.getText();
            String port = textFieldPort.getText();
            String database = textFieldDatabase.getText();
            String user = this.textFieldUser.getText();
            String password = this.textFieldPassword.getText();
            Dbms dbms = new Dbms(dbmsSelected, server, port, database, user, password);

            ArrayList executionPlan;
            try {
                AgentStatistics as = new AgentStatistics(dbms);
                executionPlan = as.getExecutionPlan(sqlIn);
                //executionPlan = ConnectionDbms.getExecutionPlan(dbms, sqlIn);

                if (executionPlan != null) {
                    text.append("PLANO DE EXECUÇÃO DA CONSULTA ORIGINAL\n\n");
                    for (Iterator it = executionPlan.iterator(); it.hasNext();) {
                        Object object = it.next();
                        text.append(object.toString()).append("\n");
                    }
                    text.append("\n\n");
                }

                String sqlOut = textAreaSqlOut.getText();
                executionPlan = as.getExecutionPlan(sqlOut);
                //executionPlan = ConnectionDbms.getExecutionPlan(dbms, sqlOut);
                if (!sqlOut.equals("")) {
                    text.append("PLANO DE EXECUÇÃO DA CONSULTA REESCRITA\n\n");
                    for (Iterator it = executionPlan.iterator(); it.hasNext();) {
                        Object object = it.next();
                        text.append(object.toString()).append("\n");
                    }
                }
                this.textAreaExecutionPlan.setText(text.toString());
                Dimension paneSize = dialogExecutionPlan.getSize();
                Dimension screenSize = dialogExecutionPlan.getToolkit().getScreenSize();
                dialogExecutionPlan.setLocation((screenSize.width - paneSize.width) / 2, (screenSize.height - paneSize.height) / 2);
                dialogExecutionPlan.setVisible(true);
            } catch (ClassNotFoundException ex) {
                JOptionPane.showMessageDialog(null, ex.getMessage());
            } catch (SQLException ex) {
                JOptionPane.showMessageDialog(null, ex.getMessage());
            }
            catch (DbmsException ex) {
                JOptionPane.showMessageDialog(null, ex.getMessage());
                    //Logger.getLogger(AdvisorGUI.class.getName()).log(Level.SEVERE, null, ex);
                }
        }
    }//GEN-LAST:event_jButton8ActionPerformed

    private void jButton9ActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_jButton9ActionPerformed
        StringBuilder text = new StringBuilder();
        String sqlOut = textAreaSqlOut.getText();
        if (!sqlOut.equals("")) {
            int dbmsSelected = this.getDbmsSelected();
            String server = this.textFieldServer.getText();
            String port = textFieldPort.getText();
            String database = textFieldDatabase.getText();
            String user = this.textFieldUser.getText();
            String password = this.textFieldPassword.getText();
            Dbms dbms = new Dbms(dbmsSelected, server, port, database, user, password);

            ArrayList executionPlan;
            try {
                AgentStatistics as = new AgentStatistics(dbms);
                executionPlan = as.getExecutionPlan(sqlOut);
                //executionPlan = ConnectionDbms.getExecutionPlan(dbms, sqlOut);

                if (sqlOut != null && !sqlOut.equals("")) {
                    text.append("PLANO DE EXECUÇÃO DA CONSULTA REESCRITA\n\n");
                    for (Iterator it = executionPlan.iterator(); it.hasNext();) {
                        Object object = it.next();
                        text.append(object.toString()).append("\n");
                    }
                    text.append("\n\n");
                }

                String sqlIn = textAreaSqlIn.getText();
                executionPlan = as.getExecutionPlan(sqlIn);
                //executionPlan = ConnectionDbms.getExecutionPlan(dbms, sqlIn);
                if (sqlOut != null && !sqlOut.equals("")) {
                    text.append("PLANO DE EXECUÇÃO DA CONSULTA ORIGINAL\n\n");
                    for (Iterator it = executionPlan.iterator(); it.hasNext();) {
                        Object object = it.next();
                        text.append(object.toString()).append("\n");
                    }
                }
                this.textAreaExecutionPlan.setText(text.toString());
                Dimension paneSize = dialogExecutionPlan.getSize();
                Dimension screenSize = dialogExecutionPlan.getToolkit().getScreenSize();
                dialogExecutionPlan.setLocation((screenSize.width - paneSize.width) / 2, (screenSize.height - paneSize.height) / 2);
                dialogExecutionPlan.setVisible(true);
            } catch (ClassNotFoundException ex) {
                JOptionPane.showMessageDialog(null, ex.getMessage());
            } catch (SQLException ex) {
                JOptionPane.showMessageDialog(null, ex.getMessage());
            } catch (DbmsException ex) {
                JOptionPane.showMessageDialog(null, ex.getMessage());
                //Logger.getLogger(AdvisorGUI.class.getName()).log(Level.SEVERE, null, ex);
            }
        }
    }//GEN-LAST:event_jButton9ActionPerformed

    private void buttonStartAdvisorActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_buttonStartAdvisorActionPerformed
        if (buttonStartAdvisor.getText().endsWith("Iniciar Advisor")) {
            int dbmsSelected = this.getDbmsSelected();
            String server = this.textFieldServer.getText();
            String port = textFieldPort.getText();
            String database = textFieldDatabase.getText();
            String user = this.textFieldUser.getText();
            String password = this.textFieldPassword.getText();
            Dbms dbms = new Dbms(dbmsSelected, server, port, database, user, password);
            /*
             if (radioSettingsToAllSql.isSelected()) {
             allSql = true;
             customSql = false;
             } else if (radioSettingsToAllSqlExceptToCustom.isSelected()) {
             allSql = true;
             customSql = true;
             } else if (radioSettingsToCustom.isSelected()) {
             allSql = false;
             customSql = true;
             } else {
             allSql = false;
             customSql = false;
             }

             */
            boolean result = ConnectionDbms.testConnection(dbms);
            if (!result) {
                labelNoConnection.setText("A conexão como o banco de dados falhou!");
            } else {
                labelNoConnection.setText("");
                long timeInterval;

                try {
                    timeInterval = Long.parseLong(this.textTimeInterval.getText());
                } catch (NumberFormatException ex) {
                    timeInterval = 5 * 60 * 1000;
                    textTimeInterval.setText(Long.toString(timeInterval));
                }

                executeAdvisor = new ExecuteAdvisor(dbms, timeInterval, "", buttonStartAdvisor);
                executeAdvisor.start();
                buttonStartAdvisor.setText("Parar Advisor");
            }
        } else {
            executeAdvisor.suspend();
            buttonStartAdvisor.setText("Iniciar Advisor");
        }
    }//GEN-LAST:event_buttonStartAdvisorActionPerformed

    private void jButton2ActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_jButton2ActionPerformed
        ProcessBuilder builder = new ProcessBuilder("notepad.exe", "WorkloadFile.txt");
        try {
            Process process = builder.start();
        } catch (IOException e) {
            JOptionPane.showMessageDialog(null, e.getMessage(), "Erro", JOptionPane.ERROR_MESSAGE);
            //e.printStackTrace();
        }
    }//GEN-LAST:event_jButton2ActionPerformed

    private void jButton7ActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_jButton7ActionPerformed
        int result = JOptionPane.showConfirmDialog(null, "Deseja realmente apagar todas as instruções SQL armazenadas?");
        if(result == JOptionPane.YES_OPTION){
            FileWriter fileWriter;
            try {
                File file = new File(fileWorkloadFile);
                fileWriter = new FileWriter(file, false);
                fileWriter.close();
            } catch (IOException ex) {
                JOptionPane.showMessageDialog(null, ex.getMessage(), "Erro", JOptionPane.ERROR_MESSAGE);
                //Logger.getLogger(AdvisorGUI.class.getName()).log(Level.SEVERE, null, ex);
            }
        }
    }//GEN-LAST:event_jButton7ActionPerformed

    private void checkBoxUseConnectionActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_checkBoxUseConnectionActionPerformed
        // TODO add your handling code here:
    }//GEN-LAST:event_checkBoxUseConnectionActionPerformed

    private void checkBoxMoveAtithmetcExpressionActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_checkBoxMoveAtithmetcExpressionActionPerformed
        // TODO add your handling code here:
    }//GEN-LAST:event_checkBoxMoveAtithmetcExpressionActionPerformed

    private void checkBoxMoveFunctionActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_checkBoxMoveFunctionActionPerformed
        // TODO add your handling code here:
    }//GEN-LAST:event_checkBoxMoveFunctionActionPerformed

    private void jButton13ActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_jButton13ActionPerformed
        ProcessBuilder builder = new ProcessBuilder("notepad.exe", "RewritesReport.txt");
        try {
            Process process = builder.start();
        } catch (IOException e) {
            JOptionPane.showMessageDialog(null, e.getMessage(), "Erro", JOptionPane.ERROR_MESSAGE);
            //e.printStackTrace();
        }
    }//GEN-LAST:event_jButton13ActionPerformed

    private void jButton10ActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_jButton10ActionPerformed
        int result = JOptionPane.showConfirmDialog(null, "Deseja apagar todos os dados da cash?");
        if (result == JOptionPane.YES_OPTION) {
            try {
                AgentRewriter.clearCash();
            } catch (IOException ex) {
                JOptionPane.showMessageDialog(null, ex.getMessage(), "Erro", JOptionPane.ERROR_MESSAGE);
                //Logger.getLogger(AdvisorGUI.class.getName()).log(Level.SEVERE, null, ex);
            }
        }

    }//GEN-LAST:event_jButton10ActionPerformed

    public class ExecuteAdvisor extends Thread {

        Dbms dbms;
        boolean allSql, customSql;
        JButton button;
        Advisor advisor;
        String path;
        long time;

        public ExecuteAdvisor(Dbms dbms, long time, String path, JButton button) {
            this.dbms = dbms;
            this.allSql = false;
            this.customSql = false;
            this.button = button;
            this.time = time;
            this.path = path;
        }

        @Override
        public void run() {
            try {
                switch (CashTypeComboBox.getSelectedIndex()) {
                    case 0:
                        advisor = new Advisor(dbms, AgentRewriter.noCash);
                        break;
                    case 1:
                        advisor = new Advisor(dbms, AgentRewriter.heuristicCash);
                        break;
                    case 2:
                        advisor = new Advisor(dbms, AgentRewriter.sqlCash);
                        break;
                }
            } catch (FileNotFoundException ex) {
                //Logger.getLogger(AdvisorGUI.class.getName()).log(Level.SEVERE, null, ex);
                System.out.println(ex.getMessage());
            } catch (IOException ex) {
                //Logger.getLogger(AdvisorGUI.class.getName()).log(Level.SEVERE, null, ex);
                System.out.println(ex.getMessage());
            }
            
            advisor.setPath(path);
            
            try {
                advisor.start(time);
            } catch (FileNotFoundException ex) {
                //Logger.getLogger(AdvisorGUI.class.getName()).log(Level.SEVERE, null, ex);
                System.out.println(ex.getMessage());
            } catch (HeuristicsSelectedException ex) {
                //Logger.getLogger(AdvisorGUI.class.getName()).log(Level.SEVERE, null, ex);
                System.out.println(ex.getMessage());
            } catch (java.text.ParseException ex) {
                System.out.println(ex.getMessage());
                //Logger.getLogger(AdvisorGUI.class.getName()).log(Level.SEVERE, null, ex);
            } catch (InterruptedException ex) {
                System.out.println(ex.getMessage());
                //Logger.getLogger(InteractiveAdvisorOnline.class.getName()).log(Level.SEVERE, null, ex);
            } catch (DbmsException ex) {
                System.out.println(ex.getMessage());
                //Logger.getLogger(InteractiveAdvisorOnline.class.getName()).log(Level.SEVERE, null, ex);
            } catch (ClassNotFoundException ex) {
                System.out.println(ex.getMessage());
                //Logger.getLogger(InteractiveAdvisorOnline.class.getName()).log(Level.SEVERE, null, ex);
            } catch (SQLException ex) {
                System.out.println(ex.getMessage());
                //Logger.getLogger(InteractiveAdvisorOnline.class.getName()).log(Level.SEVERE, null, ex);
            } catch (ParseException ex) {
                System.out.println(ex.getMessage());
                //Logger.getLogger(InteractiveAdvisorOnline.class.getName()).log(Level.SEVERE, null, ex);
            } catch (SqlInputException ex) {
                System.out.println(ex.getMessage());
                //Logger.getLogger(InteractiveAdvisorOnline.class.getName()).log(Level.SEVERE, null, ex);
            } catch (IOException ex) {
                System.out.println(ex.getMessage());
                // Logger.getLogger(InteractiveAdvisorOnline.class.getName()).log(Level.SEVERE, null, ex);
            } catch (NegativeNumberException ex) {
                System.out.println(ex.getMessage());
                // Logger.getLogger(InteractiveAdvisorOnline.class.getName()).log(Level.SEVERE, null, ex);
            }
            if (button != null) {
                button.setText("Iniciar Advisor");
            }
        }
    }

    private void setCheckBoxsAsPlain() {
        this.checkBoxAllToSubquery.setFont(checkBoxAllToSubquery.getFont().deriveFont(Font.PLAIN));
        this.checkBoxAnyToSubquery.setFont(checkBoxAnyToSubquery.getFont().deriveFont(Font.PLAIN));
        this.checkBoxHavingToWhere.setFont(checkBoxHavingToWhere.getFont().deriveFont(Font.PLAIN));
        this.checkBoxInToJoin.setFont(checkBoxInToJoin.getFont().deriveFont(Font.PLAIN));
        this.checkBoxMoveAtithmetcExpression.setFont(checkBoxMoveAtithmetcExpression.getFont().deriveFont(Font.PLAIN));
        this.checkBoxMoveFunction.setFont(checkBoxMoveFunction.getFont().deriveFont(Font.PLAIN));
        this.checkBoxOrToUnion.setFont(checkBoxOrToUnion.getFont().deriveFont(Font.PLAIN));
        this.checkBoxRemoveDistinct.setFont(checkBoxRemoveDistinct.getFont().deriveFont(Font.PLAIN));
        this.checkBoxRemoveGroupby.setFont(checkBoxRemoveGroupby.getFont().deriveFont(Font.PLAIN));
        this.checkBoxSomeToSubquery.setFont(checkBoxSomeToSubquery.getFont().deriveFont(Font.PLAIN));
        this.checkBoxTemporaryTable.setFont(checkBoxTemporaryTable.getFont().deriveFont(Font.PLAIN));
    }

    private void setCheckBoxsAsSelected() {
        this.checkBoxAllToSubquery.setSelected(true);
        this.checkBoxAnyToSubquery.setSelected(true);
        this.checkBoxHavingToWhere.setSelected(true);
        this.checkBoxInToJoin.setSelected(true);
        this.checkBoxMoveAtithmetcExpression.setSelected(true);
        this.checkBoxMoveFunction.setSelected(true);
        this.checkBoxOrToUnion.setSelected(true);
        this.checkBoxRemoveDistinct.setSelected(true);
        this.checkBoxRemoveGroupby.setSelected(true);
        this.checkBoxSomeToSubquery.setSelected(true);
        this.checkBoxTemporaryTable.setSelected(true);
    }

    private void setCheckBoxsAsHeuristicsExecuted(HeuristicsSelected heuristicsSelect) {
        if (heuristicsSelect.isAllToSubqueryExecuted()) {
            this.checkBoxAllToSubquery.setFont(checkBoxAllToSubquery.getFont().deriveFont(Font.BOLD));
        }
        if (heuristicsSelect.isAnyToSubqueryExecuted()) {
            this.checkBoxAnyToSubquery.setFont(checkBoxAnyToSubquery.getFont().deriveFont(Font.BOLD));
        }
        if (heuristicsSelect.isHavingToWhereExecuted()) {
            this.checkBoxHavingToWhere.setFont(checkBoxHavingToWhere.getFont().deriveFont(Font.BOLD));
        }
        if (heuristicsSelect.isInToJoinExecuted()) {
            this.checkBoxInToJoin.setFont(checkBoxInToJoin.getFont().deriveFont(Font.BOLD));
        }
        if (heuristicsSelect.isMoveAtithmetcExpressionExecuted()) {
            this.checkBoxMoveAtithmetcExpression.setFont(checkBoxMoveAtithmetcExpression.getFont().deriveFont(Font.BOLD));
        }
        if (heuristicsSelect.isMoveFunctionExecuted()) {
            this.checkBoxMoveFunction.setFont(checkBoxMoveFunction.getFont().deriveFont(Font.BOLD));
        }
        if (heuristicsSelect.isOrToUnionExecuted()) {
            this.checkBoxOrToUnion.setFont(checkBoxOrToUnion.getFont().deriveFont(Font.BOLD));
        }
        if (heuristicsSelect.isRemoveDistinctExecuted()) {
            this.checkBoxRemoveDistinct.setFont(checkBoxRemoveDistinct.getFont().deriveFont(Font.BOLD));
        }
        if (heuristicsSelect.isRemoveGroupbyExecuted()) {
            this.checkBoxRemoveGroupby.setFont(checkBoxRemoveGroupby.getFont().deriveFont(Font.BOLD));
        }
        if (heuristicsSelect.isSomeToSubqueryExecuted()) {
            this.checkBoxSomeToSubquery.setFont(checkBoxSomeToSubquery.getFont().deriveFont(Font.BOLD));
        }
        if (heuristicsSelect.isTemporaryTableToSubQueryExecuted()) {
            this.checkBoxTemporaryTable.setFont(checkBoxTemporaryTable.getFont().deriveFont(Font.BOLD));
        }
    }

    private void setHeuristicsSelected(HeuristicsSelected heuristicsSelect) {
        heuristicsSelect.setAllToSubquerySelected(this.checkBoxAllToSubquery.isSelected());
        heuristicsSelect.setAnyToSubquerySelected(this.checkBoxAnyToSubquery.isSelected());
        heuristicsSelect.setHavingToWhereSelected(this.checkBoxHavingToWhere.isSelected());
        heuristicsSelect.setInToJoinSelected(this.checkBoxInToJoin.isSelected());
        heuristicsSelect.setMoveAtithmetcExpressionSelected(this.checkBoxMoveAtithmetcExpression.isSelected());
        heuristicsSelect.setMoveFunctionSelected(this.checkBoxMoveFunction.isSelected());
        heuristicsSelect.setOrToUnionSelected(this.checkBoxOrToUnion.isSelected());
        heuristicsSelect.setRemoveDistinctSelected(this.checkBoxRemoveDistinct.isSelected());
        heuristicsSelect.setRemoveGroupbySelected(this.checkBoxRemoveGroupby.isSelected());
        heuristicsSelect.setSomeToSubquerySelected(this.checkBoxSomeToSubquery.isSelected());
        heuristicsSelect.setTemporaryTableToSubQuerySelected(this.checkBoxTemporaryTable.isSelected());
    }

    private int getDbmsSelected() {
        int dbms = comboBoxBdms.getSelectedIndex();
        switch (dbms) {
            case 0:
                return Dbms.POSTGRESQL;
            case 1:
                return Dbms.SQLSERVER;
            case 2:
                return Dbms.ORACLE;
        }
        return -1;
    }

    private boolean getCheckBoxState(String fileName) {
        try {
            File file = new File(fileName);
            FileInputStream fis = new FileInputStream(file);

            Properties props = new Properties();
            //lê os dados que estão no arquivo
            props.load(fis);
            fis.close();

            //lê proriedades do arquivo
            String state = props.getProperty("state");
            if (state.equalsIgnoreCase("true")) {
                return true;
            }
        } catch (IOException ex) {
            System.out.println("Errro em getCheckBoxState(): " + ex.getMessage());
            return false;
        }
        return false;
    }

    private void saveCheckBoxState(String fileName, boolean state) {
        //o arquivo encontra-se no mesmo diretório da aplicação
        try {
            File file = new File(fileName);
            FileOutputStream fos = new FileOutputStream(file);

            Properties props = new Properties();
            //grava propreidades  no arquivo
            props.setProperty("state", Boolean.toString(state));

            props.store(fos, "Armazena estado do checkbox.");
            fos.close();
        } catch (IOException ex) {
            System.out.println("Errro em saveCheckBoxState(): " + ex.getMessage());
        }
    }

    private void saveSelectedDatabase() {
        //o arquivo encontra-se no mesmo diretório da aplicação
        int number = comboBoxBdms.getSelectedIndex();
        try {
            File file = new File(fileNameSelectedDatabase);
            FileOutputStream fos = new FileOutputStream(file);

            Properties props = new Properties();
            //grava propreidades  no arquivo
            props.setProperty("database", Integer.toString(number));

            props.store(fos, "Número do último banco de dados selecionado no checkbox.");
            fos.close();
        } catch (IOException ex) {
            System.out.println("Errro em setSelectedDatabase(): " + ex.getMessage());
        }
    }

    private int getSelectedDatabase() {
        try {
            File file = new File(fileNameSelectedDatabase);
            FileInputStream fis = new FileInputStream(file);

            Properties props = new Properties();
            //lê os dados que estão no arquivo
            props.load(fis);
            fis.close();

            //lê proriedades do arquivo
            String database = props.getProperty("database");
            return Integer.parseInt(database);
        } catch (IOException ex) {
            System.out.println("Errro em getSelectedDatabase(): " + ex.getMessage());;
            return 0;
        }
    }

    private void saveDatabaseSettings() {
        String fileName = "";
        switch (this.getDbmsSelected()) {
            case Dbms.POSTGRESQL:
                fileName = fileNamePostgresql;
                break;
            case Dbms.SQLSERVER:
                fileName = fileNameSqlserver;
                break;
            case Dbms.ORACLE:
                fileName = fileNameOracle;
                break;
        }

        //o arquivo encontra-se no mesmo diretório da aplicação
        try {
            File file = new File(fileName);
            FileOutputStream fos = new FileOutputStream(file);

            String server = this.textFieldServer.getText();
            String port = textFieldPort.getText();
            String database = textFieldDatabase.getText();
            String user = this.textFieldUser.getText();
            String password = this.textFieldPassword.getText();
            boolean isSavedPassword = this.checkBoxSavePassword.isSelected();

            Properties props = new Properties();
            //grava propreidades  no arquivo
            props.setProperty("server", server);
            props.setProperty("port", port);
            props.setProperty("database", database);
            props.setProperty("user", user);
            if (isSavedPassword) {
                props.setProperty("password", password);
            } else {
                props.setProperty("password", "");
            }

            props.store(fos, "Configurações do BD");
            fos.close();
        } catch (IOException ex) {
            System.out.println("Errro em setDatabaseSettings(): " + ex.getMessage());
        }
    }

    private void getDatabaseSettings() {
        String fileName = "";
        switch (this.getDbmsSelected()) {
            case Dbms.POSTGRESQL:
                fileName = fileNamePostgresql;
                break;
            case Dbms.SQLSERVER:
                fileName = fileNameSqlserver;
                break;
            case Dbms.ORACLE:
                fileName = fileNameOracle;
                break;
        }

        try {
            File file = new File(fileName);
            FileInputStream fis = new FileInputStream(file);

            Properties props = new Properties();
            //lê os dados que estão no arquivo
            props.load(fis);
            fis.close();

            //lê proriedades do arquivo
            String server = props.getProperty("server");
            String port = props.getProperty("port");
            String database = props.getProperty("database");
            String user = props.getProperty("user");
            String password = props.getProperty("password");

            this.textFieldServer.setText(server);
            this.textFieldPort.setText(port);
            this.textFieldDatabase.setText(database);
            this.textFieldUser.setText(user);
            this.textFieldPassword.setText(password);

        } catch (IOException ex) {
            System.out.println("Errro em getSelectedDatabase(): " + ex.getMessage());;
        }
    }

    class SqlTime {

        public String time;
    }

    public class ExecuteQuery extends Thread {

        Dbms dbms;
        String sql;
        JLabel label;
        JButton button;

        public ExecuteQuery(Dbms dbms, String sql, JLabel label, JButton button) {
            this.dbms = dbms;
            this.sql = sql;
            this.label = label;
            this.button = button;
        }

        @Override
        public void run() {
            String time;
            try {
                AgentStatistics as = new AgentStatistics(dbms);
                time = as.getRealRuntime(sql);
                //time = ConnectionDbms.getRuntime(dbms, sql);
            } catch (ClassNotFoundException ex) {
                time = ex.getMessage();
                System.out.println(ex.getMessage());
            } catch (SQLException ex) {
                time = ex.getMessage();
                System.out.println(ex.getMessage());
            } catch (DbmsException ex) {
                time = ex.getMessage();
                System.out.println(ex.getMessage());
                //Logger.getLogger(AdvisorGUI.class.getName()).log(Level.SEVERE, null, ex);
            }
            if (label != null) {
                label.setText(time);
            }
            if (button != null) {
                button.setText("Executar SQL");
            }
        }
    }

    /**
     * @param args the command line arguments
     */
    public static void main(String args[]) {
        /* Set the Nimbus look and feel */
        //<editor-fold defaultstate="collapsed" desc=" Look and feel setting code (optional) ">
        /* If Nimbus (introduced in Java SE 6) is not available, stay with the default look and feel.
         * For details see http://download.oracle.com/javase/tutorial/uiswing/lookandfeel/plaf.html 
         */
        try {
            for (javax.swing.UIManager.LookAndFeelInfo info : javax.swing.UIManager.getInstalledLookAndFeels()) {
                if ("Nimbus".equals(info.getName())) {
                    javax.swing.UIManager.setLookAndFeel(info.getClassName());
                    break;
                }
            }
        } catch (ClassNotFoundException ex) {
            java.util.logging.Logger.getLogger(AdvisorGUI.class.getName()).log(java.util.logging.Level.SEVERE, null, ex);
        } catch (InstantiationException ex) {
            java.util.logging.Logger.getLogger(AdvisorGUI.class.getName()).log(java.util.logging.Level.SEVERE, null, ex);
        } catch (IllegalAccessException ex) {
            java.util.logging.Logger.getLogger(AdvisorGUI.class.getName()).log(java.util.logging.Level.SEVERE, null, ex);
        } catch (javax.swing.UnsupportedLookAndFeelException ex) {
            java.util.logging.Logger.getLogger(AdvisorGUI.class.getName()).log(java.util.logging.Level.SEVERE, null, ex);
        }
        //</editor-fold>

        /* Create and display the form */
        java.awt.EventQueue.invokeLater(new Runnable() {
            @Override
            public void run() {
                new AdvisorGUI().setVisible(true);
            }
        });
    }
    // Variables declaration - do not modify//GEN-BEGIN:variables
    private javax.swing.JComboBox CashTypeComboBox;
    private javax.swing.JButton buttonExecuteSqlIn;
    private javax.swing.JButton buttonExecuteSqlOut;
    private javax.swing.ButtonGroup buttonGroup1;
    private javax.swing.JButton buttonStartAdvisor;
    private javax.swing.JCheckBox checkBoxAllToSubquery;
    private javax.swing.JCheckBox checkBoxAnyToSubquery;
    private javax.swing.JCheckBox checkBoxHavingToWhere;
    private javax.swing.JCheckBox checkBoxIdentSQLIn;
    private javax.swing.JCheckBox checkBoxIdentSQLOut;
    private javax.swing.JCheckBox checkBoxInToJoin;
    private javax.swing.JCheckBox checkBoxMoveAtithmetcExpression;
    private javax.swing.JCheckBox checkBoxMoveFunction;
    private javax.swing.JCheckBox checkBoxOrToUnion;
    private javax.swing.JCheckBox checkBoxRemoveDistinct;
    private javax.swing.JCheckBox checkBoxRemoveGroupby;
    private javax.swing.JCheckBox checkBoxSavePassword;
    private javax.swing.JCheckBox checkBoxSomeToSubquery;
    private javax.swing.JCheckBox checkBoxTemporaryTable;
    private javax.swing.JCheckBox checkBoxUseConnection;
    private javax.swing.JComboBox comboBoxBdms;
    private javax.swing.JDialog dialogCustomSettings;
    private javax.swing.JDialog dialogDefaultSettings;
    private javax.swing.JDialog dialogExecutionPlan;
    private javax.swing.JDialog dialogRelatorio;
    private javax.swing.JButton jButton1;
    private javax.swing.JButton jButton10;
    private javax.swing.JButton jButton13;
    private javax.swing.JButton jButton2;
    private javax.swing.JButton jButton3;
    private javax.swing.JButton jButton4;
    private javax.swing.JButton jButton5;
    private javax.swing.JButton jButton6;
    private javax.swing.JButton jButton7;
    private javax.swing.JButton jButton8;
    private javax.swing.JButton jButton9;
    private javax.swing.JCheckBox jCheckBox1;
    private javax.swing.JLabel jLabel1;
    private javax.swing.JLabel jLabel10;
    private javax.swing.JLabel jLabel11;
    private javax.swing.JLabel jLabel12;
    private javax.swing.JLabel jLabel13;
    private javax.swing.JLabel jLabel14;
    private javax.swing.JLabel jLabel15;
    private javax.swing.JLabel jLabel17;
    private javax.swing.JLabel jLabel18;
    private javax.swing.JLabel jLabel19;
    private javax.swing.JLabel jLabel2;
    private javax.swing.JLabel jLabel20;
    private javax.swing.JLabel jLabel21;
    private javax.swing.JLabel jLabel22;
    private javax.swing.JLabel jLabel23;
    private javax.swing.JLabel jLabel24;
    private javax.swing.JLabel jLabel25;
    private javax.swing.JLabel jLabel26;
    private javax.swing.JLabel jLabel27;
    private javax.swing.JLabel jLabel28;
    private javax.swing.JLabel jLabel29;
    private javax.swing.JLabel jLabel3;
    private javax.swing.JLabel jLabel30;
    private javax.swing.JLabel jLabel31;
    private javax.swing.JLabel jLabel4;
    private javax.swing.JLabel jLabel5;
    private javax.swing.JLabel jLabel6;
    private javax.swing.JLabel jLabel7;
    private javax.swing.JLabel jLabel8;
    private javax.swing.JLabel jLabel9;
    private javax.swing.JPanel jPanel1;
    private javax.swing.JPanel jPanel10;
    private javax.swing.JPanel jPanel11;
    private javax.swing.JPanel jPanel12;
    private javax.swing.JPanel jPanel13;
    private javax.swing.JPanel jPanel14;
    private javax.swing.JPanel jPanel15;
    private javax.swing.JPanel jPanel16;
    private javax.swing.JPanel jPanel17;
    private javax.swing.JPanel jPanel18;
    private javax.swing.JPanel jPanel19;
    private javax.swing.JPanel jPanel2;
    private javax.swing.JPanel jPanel20;
    private javax.swing.JPanel jPanel21;
    private javax.swing.JPanel jPanel22;
    private javax.swing.JPanel jPanel23;
    private javax.swing.JPanel jPanel24;
    private javax.swing.JPanel jPanel25;
    private javax.swing.JPanel jPanel26;
    private javax.swing.JPanel jPanel27;
    private javax.swing.JPanel jPanel28;
    private javax.swing.JPanel jPanel29;
    private javax.swing.JPanel jPanel3;
    private javax.swing.JPanel jPanel30;
    private javax.swing.JPanel jPanel32;
    private javax.swing.JPanel jPanel33;
    private javax.swing.JPanel jPanel34;
    private javax.swing.JPanel jPanel4;
    private javax.swing.JPanel jPanel5;
    private javax.swing.JPanel jPanel6;
    private javax.swing.JPanel jPanel7;
    private javax.swing.JPanel jPanel8;
    private javax.swing.JPanel jPanel9;
    private javax.swing.JScrollPane jScrollPane1;
    private javax.swing.JScrollPane jScrollPane2;
    private javax.swing.JScrollPane jScrollPane3;
    private javax.swing.JScrollPane jScrollPane4;
    private javax.swing.JScrollPane jScrollPane5;
    private javax.swing.JScrollPane jScrollPane6;
    private javax.swing.JScrollPane jScrollPane7;
    private javax.swing.JToggleButton jToggleButton1;
    private javax.swing.JToggleButton jToggleButton2;
    private javax.swing.JLabel labelAddRewriteSettings;
    private javax.swing.JLabel labelExecutingRewrite;
    private javax.swing.JLabel labelMessengeRewrite;
    private javax.swing.JLabel labelNoConnection;
    private javax.swing.JLabel labelRewriteError;
    private javax.swing.JLabel labelSqlInResult;
    private javax.swing.JLabel labelSqlOutResult;
    private javax.swing.JList listSqlsFromFile;
    private javax.swing.JPanel panelCenter;
    private javax.swing.JPanel panelCenterLeft;
    private javax.swing.JPanel panelCenterLeftBottom;
    private javax.swing.JPanel panelCenterLeftTop;
    private javax.swing.JPanel panelCenterRight;
    private javax.swing.JPanel panelHeuristics;
    private javax.swing.JPanel panelInteractive;
    private javax.swing.JPanel panelMain;
    private javax.swing.JPanel panelNorth;
    private javax.swing.JPanel panelNorthLeft;
    private javax.swing.JPanel panelNorthRight;
    private javax.swing.JPanel panelReewriteButtons;
    private javax.swing.JTable tableCustomHeuristics;
    private javax.swing.JTextArea textAreaDefaultSettings;
    private javax.swing.JTextArea textAreaExecutionPlan;
    private javax.swing.JTextArea textAreaRelatorio;
    private javax.swing.JTextArea textAreaSqlIn;
    private javax.swing.JTextArea textAreaSqlOut;
    private javax.swing.JTextField textFieldDatabase;
    private javax.swing.JTextField textFieldPassword;
    private javax.swing.JTextField textFieldPort;
    private javax.swing.JTextField textFieldServer;
    private javax.swing.JTextField textFieldUser;
    private javax.swing.JTextField textTimeInterval;
    // End of variables declaration//GEN-END:variables
}
